<template>
  <div style="padding: 10px">
    <el-row :gutter="20">
      <el-col :span="6" />
      <el-col :span="6">
        <el-button
          type="text"
          icon="el-icon-download"
          @click="Generatefiles = true"
          >生成自定义报告
        </el-button>
      </el-col>
      <el-col :span="12" />
    </el-row>
    <el-row :gutter="20">
      <el-col :span="8">
        <el-table
          ref="table"
          v-loading="crud.loading"
          highlight-current-row
          :data="res1"
          @current-change="checkboxT"
        >
          <el-table-column label="文件名称" align="center" prop="fileName" />
        </el-table>
      </el-col>
      <el-col :span="16">
        <el-table
          ref="table"
          v-loading="tableLoading"
          :data="tableList"
          show-header="true"
          max-height="800"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column value="表格数据" align="center">
            <template slot-scope="scope">
              <Table :data="scope.row.tables" :t-nember="scope.row.tNember" />
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-dialog :visible.sync="Generatefiles">
      <el-form :data="crud.data">
        <el-form-item label="名称" :label-width="formLabelWidth">
          <el-input v-model="mainname" autocomplete="off" />
        </el-form-item>
        <el-form-item label="模板" :label-width="formLabelWidth">
          <el-select v-model="fileName" placeholder="请选择活动区域">
            <el-option
              v-for="item in doctype1"
              :key="item.name"
              :value="item.fileName"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="Generatefiles = false">取 消</el-button>
        <el-button type="primary" @click="Generate()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
// 问题出在这   这个地方引入的时候为undefined了 之前写法不对  有{}  去掉后就可以了
import getaxios from "@/api/system/document";
import { initData, download } from "@/api/data";
import Table from "@/views/sid/marge/table.vue";
import CRUD, { presenter, header, form, crud } from "@crud/crud";
import DateRangePicker from "@/components/DateRangePicker";
import Treeselect from "@riophae/vue-treeselect";
import { mapGetters } from "vuex";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { LOAD_CHILDREN_OPTIONS } from "@riophae/vue-treeselect";

let userRoles = [];
let userJobs = [];
const defaultForm = {
  id: null,
  username: null,
  nickName: null,
  gender: "男",
  email: null,
  enabled: "false",
  rightlist: [],
  jobs: [],
  dept: { id: null },
  phone: null,
};
export default {
  name: "User",
  components: {
    Treeselect,
    DateRangePicker,
    Table,
  },
  cruds() {
    // 成功的通讯是基于这个类发的
    return CRUD({
      title: "安全",
      url: "api/document",
      params: {
        docType: "2",
      },
      crudMethod: { ...getaxios },
    });
  },

  // cruds1() {
  //   return CRUD({
  //     title: "安全",
  //     url: "api/document/tablelist",
  //     params: {
  //       docType: "0"
  //     },
  //     crudMethod: { ...list }
  //   });
  // },
  mixins: [presenter(), header(), form(defaultForm), crud()],

  data() {
    // 自定义验证

    return {
      // 多选数据列表
      tableId: "",
      tables: [],
      tabless: [],
      tableLoading: false,
      filenamelist: [], // 列表1
      fileshow: false,
      tablelists: [], // 列表二选中数据
      familyListList: [],
      mainname: "",
      fileName: "",
      doctype1: [],
      res1: [],
      file: "",
      downloadLoading: false,
      //   height: document.documentElement.clientHeight - 180 + "px;",
      // 自定义报告弹窗
      Generatefiles: false,
      formLabelWidth: "120px",
      tableList: [],
      depts: [],
      deptDatas: [],
      jobs: [],
      level: 3,
      rightlist: [],
      roles: [],
      jobDatas: [],
      roleDatas: [], // 多选时使用
      defaultProps: { children: "children", label: "name", isLeaf: "leaf" },
      permission: {
        // add: ["admin", "user:add"],
        edit: ["admin", "user:edit"],
        del: ["admin", "user:del"],
        // gettablelist: ["admin", "user:gettablelist"],
      },
      //   enabledTypeOptions: [
      //     { key: "true", display_name: "激活" },
      //     { key: "false", display_name: "锁定" }
      //   ],
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "长度在 2 到 20 个字符",
            trigger: "blur",
          },
        ],
        nickName: [
          { required: true, message: "请输入用户昵称", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "长度在 2 到 20 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
        ],
        // phone: [{ required: true, trigger: "blur", validator: validPhone }]
      },
    };
  },
  computed: {
    ...mapGetters(["user"]),
  },
  created() {
    // selectfile();
    // console.log(this.res1);
    // console.log(this.crud);
    // debugger;
    // for (let i = 0; i < this.curd.data.length; i++) {
    //   let dataTale = table.rows;
    // }
  },
  mounted() {
    // this.tablelist1(); //2列表渲染调用
    this.selectfile(); // 获取下拉框的值
    console.log(this.crud, "======");
    getaxios
      .getlist({
        // todo  应该是需要传参的
        docType: "0",
      })
      .then((res) => {
        console.log("111???????2");
        console.log(res, "getdocument");
        console.log(this.crud);
        this.res1 = res;

        // this.crud.notify(
        //   this.dict.label.user_status[val] + "成功",
        //   CRUD.NOTIFICATION_TYPE.SUCCESS
        // );
      })
      .catch((err) => {
        // 应该是没传参的问题  进catch了
        console.log("1113");
        // data.enabled = !data.enabled;
      });
  },
  methods: {
    // 合并文件
    merge() {
      alert("成功");
      this.$router.push({ name: "custom" });
    },

    upload() {
      this.$refs.upload.submit();
    },

    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      console.log(this.getlist());
      if (form.id == null) {
        this.getDepts();
      } else {
        this.getSupDepts(form.dept.id);
      }
      this.getRoleLevel();
      this.getJobs();
      form.enabled = form.enabled.toString();
    },
    // 新增前将多选的值设置为空
    [CRUD.HOOK.beforeToAdd]() {
      this.jobDatas = [];
      this.roleDatas = [];
    },
    // 初始化编辑时候的角色与岗位
    [CRUD.HOOK.beforeToEdit](crud, form) {
      this.getJobs(this.form.dept.id);
      this.jobDatas = [];
      this.roleDatas = [];
      userRoles = [];
      userJobs = [];
      const _this = this;
      form.roles.forEach(function (role, index) {
        _this.roleDatas.push(role.id);
        const rol = { id: role.id };
        userRoles.push(rol);
      });
      form.jobs.forEach(function (job, index) {
        _this.jobDatas.push(job.id);
        const data = { id: job.id };
        userJobs.push(data);
      });
    },
    // 提交前做的操作
    [CRUD.HOOK.afterValidateCU](crud) {
      if (!crud.form.dept.id) {
        this.$message({
          message: "部门不能为空",
          type: "warning",
        });
        return false;
      } else if (this.jobDatas.length === 0) {
        this.$message({
          message: "岗位不能为空",
          type: "warning",
        });
        return false;
      } else if (this.roleDatas.length === 0) {
        this.$message({
          message: "角色不能为空",
          type: "warning",
        });
        return false;
      }
      crud.form.roles = userRoles;
      crud.form.jobs = userJobs;
      return true;
    },
    // 获取左侧部门数据
    getDepts() {
      getDepts({ enabled: true }).then((res) => {
        this.depts = res.content.map(function (obj) {
          if (obj.hasChildren) {
            obj.children = null;
          }
          return obj;
        });
      });
    },
    getSupDepts(deptId) {
      getDeptSuperior(deptId).then((res) => {
        const date = res.content;
        this.buildDepts(date);
        this.depts = date;
      });
    },
    buildDepts(depts) {
      depts.forEach((data) => {
        if (data.children) {
          this.buildDepts(data.children);
        }
        if (data.hasChildren && !data.children) {
          data.children = null;
        }
      });
    },
    // 下拉框取模板值
    selectfile() {
      getaxios
        .getdocument({
          // todo  应该是需要传参的
          docType: "2",
        })
        .then((res) => {
          console.log(res);
          console.log(res.content);
          this.doctype1 = res.content;
          console.log(this.doctype1);
          // this.doctype1.push(res);
          // console.log(this.doctype1);
        })
        .catch((err) => {
          // 应该是没传参的问题  进catch了
          console.log("1113");
          // data.enabled = !data.enabled;
        });
    },
    checkboxT(row) {
      this.tableId = row.id;
      this.tableLoading = true;
      getaxios
        .gettablelist({
          // todo  应该是需要传参的
          documentId: row.id,
        })
        .then((res) => {
          this.tableList = [];
          this.familyListList = [];
          // this.res1 = res;
          for (let i = 0; i < res.length; i++) {
            // 表格
            const familyList1 = [];
            const table = res[i];
            // 数据库中数据转化
            const tableRows = JSON.parse(table.rows);
            // 每一行数据
            for (let j = 0; j < tableRows.length; j++) {
              // 行中每一列的数据
              const cells = tableRows[j].cells;
              const text = [];
              for (let k = 0; k < cells.length; k++) {
                // 中有段落
                const paragraphs = cells[k].paragraphs;
                // 每一个表格中的文本
                let paragraphText = "";
                for (let m = 0; m < paragraphs.length; m++) {
                  paragraphText = paragraphText + paragraphs[m].text;
                }
                const key = "t" + k;
                text[key] = paragraphText;
              }
              // 将表格中每一列的数据填充到表格里
              familyList1.push(text);
            }
            // 将每一个表格填充到map中
            res[i].tables = familyList1;
            this.tableList.push(res[i]);
            this.tableList[i].tables = familyList1;
            this.tableList[i].tNember = tableRows[0].cells.length;
          }
          this.tableList = res;
          this.tableLoading = false;
        })
        .catch((err) => {
          // 应该是没传参的问题  进catch了
          console.log(err);
          // data.enabled = !data.enabled;
        });
    },
    // 2列表
    // tablelist1() {},

    // 多选框
    handleSelectionChange(val, index) {
      this.tables = val;
      this.tabless[this.tableId] = val;
    },
    // 点击确定调取生成按钮接口
    Generate() {
      // 获取跨项目数据
      let documentTables = "";
      for (let i = 0; i < this.res1.length; i++) {
        const lists = this.tabless[this.res1[i].id];
        if (lists != null) {
          for (let j = 0; j < lists.length; j++) {
            documentTables = documentTables + "," + lists[j].id;
          }
        }
      }
      getaxios
        .getgenerate({
          // todo  应该是需要传参的
          head: this.mainname,
          templateName: this.fileName, // 选择模板数据
          documentTables: documentTables,
        })
        .then((res) => {
          console.log(res);
          console.log(res[0].rows);
          this.tablelist = res[0];
          this.Generatefiles = false;
        })
        .catch((err) => {
          // 应该是没传参的问题  进catch了
          console.log("1113");
          // data.enabled = !data.enabled;
        });
      console.log(this.tablelist);
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .vue-treeselect__control,
::v-deep .vue-treeselect__placeholder,
::v-deep .vue-treeselect__single-value {
  height: 30px;
  line-height: 30px;
}
</style>
